using System;
using System.Security.Cryptography;

namespace SharpObjects.Cryptography.DigitalSignature
{
	/// <summary>
	/// Summary description for DsaProvider.
	/// </summary>
	public class DsaProvider : ICryptoProvider, IDigitalSignatureProvider
	{
		protected DSACryptoServiceProvider m_provider = null;
		protected bool m_bHidePrivateKey = false;

		public DsaProvider()
		{
			m_provider = new DSACryptoServiceProvider();
		}

		public DsaProvider(DSAParameters parameters)
		{
			m_provider.ImportParameters(parameters);
		}

		public bool HidePrivateKey { get { return m_bHidePrivateKey; } set { m_bHidePrivateKey = value; } }

		//#region ICryptoProvider Members


		byte [] ICryptoProvider.Encrypt(byte [] data)
		{
			throw new InvalidOperationException("Encrypt() is not implemented on DsaProvider");
		}

		byte [] ICryptoProvider.Decrypt(byte [] data)
		{
			throw new InvalidOperationException("Decrypt() is not implemented on DsaProvider");
		}

		public ICryptoKey CryptoKey 
		{
			get
			{
				DsaKey key = new DsaKey(m_provider.ExportParameters(! m_bHidePrivateKey));
				return (ICryptoKey)key;
			}
			set
			{
				DsaKey key = (DsaKey)value;
				m_provider.ImportParameters(key);
			}
		}

		//#endregion

		//#region IDigitalSignatureProvider Members

		public byte[] GetHash(byte[] data)
		{
			byte[] sha1_hash;
			SHA1 shaM = new SHA1Managed();
			sha1_hash = shaM.ComputeHash(data);
			return sha1_hash;
		}

		public byte[] Sign(byte[] sha1_hash)
		{
			DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(m_provider);
			DSAFormatter.SetHashAlgorithm("SHA1"); // SHA1 - default and only value
			return DSAFormatter.CreateSignature(sha1_hash);
		}

		public bool Verify(byte[] sha1_hash, byte[] signature)
		{
			DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(m_provider);
			DSADeformatter.SetHashAlgorithm("SHA1"); // SHA1 - default and only value
			return DSADeformatter.VerifySignature(sha1_hash, signature);
		}

		//#endregion
	}
}
